package com.ys.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ys.entity.WalletDeposit;
import com.ys.entity.WalletWithdraw;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@Slf4j
@ConfigurationProperties(prefix="notify")
@Data
public class NotifyService {

    //通知的url
    private String depositUrl;
    private String withdrawUrl;
    private String ssl;


    @Autowired
    private WalletDepositServiceImap walletDepositServiceImap;

    @Autowired
    private WalletWithdrawServiceImap walletWithdrawServiceImap;

    @Autowired
    private RestTemplate restTemplate;

    public void notifyDeposit(){
        EntityWrapper<WalletDeposit> ew = new EntityWrapper<WalletDeposit>();
        ew.ge("status",20);
        ew.lt("status",40);
        List<WalletDeposit> list=walletDepositServiceImap.selectList(ew);
        if(CollUtil.isEmpty(list)){
            log.info("冲币通知可用任务为空");
            return ;
        }
        for(WalletDeposit walletDeposit:list){
            sendNotifyDeposit(walletDeposit);
        }

    }

    public void notifyWithdraw(){
        EntityWrapper<WalletWithdraw> ew = new EntityWrapper<WalletWithdraw>();
        ew.ge("status",30);
        ew.lt("status",40);
        List<WalletWithdraw> list=walletWithdrawServiceImap.selectList(ew);
        if(CollUtil.isEmpty(list)){
            log.info("提币通知可用任务为空");
            return ;
        }
        for(WalletWithdraw walletWithdraw:list){
            sendNotifyWithdraw(walletWithdraw);
        }

    }

    /**
     * 发送冲币成功通知
     * @param walletDeposit
     */
    public void sendNotifyDeposit(WalletDeposit walletDeposit){
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, Object> params= new LinkedMultiValueMap();

        params.add("currency", walletDeposit.getCurrency().toString());
        params.add("currencyChainType", walletDeposit.getCurrencyChainType().toString());
        params.add("txHash",walletDeposit.getTxHash());
        params.add("depositAmount",walletDeposit.getDepositAmount().toString());
        params.add("inputDate",walletDeposit.getInputDate().toString());
        params.add("id",walletDeposit.getId().toString());

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, initHttpHeader());
       //执行HTTP请求
        ResponseEntity<String> response = restTemplate.exchange(depositUrl, HttpMethod.POST, requestEntity, String.class);
        WalletDeposit wdUpdateStatus=new WalletDeposit();
        wdUpdateStatus.setId(walletDeposit.getId());
        /**更新成功**/
        if(response!=null && response.getBody()!=null && response.getBody().contains("success")){
            wdUpdateStatus.setStatus(40);
        }else{
            if(walletDeposit.getStatus()==20)
                wdUpdateStatus.setStatus(30);
            else if(walletDeposit.getStatus()<33)
                wdUpdateStatus.setStatus(walletDeposit.getStatus()+1);
            log.info("冲币成功,通知失败：walletDeposit="+ JSONUtil.toJsonStr(walletDeposit));
        }
        walletDepositServiceImap.updateById(wdUpdateStatus);
    }


    /**
     * 发送提币成功通知
     * @param walletWithdraw
     */
    public void sendNotifyWithdraw(WalletWithdraw walletWithdraw){
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, Object> params= new LinkedMultiValueMap<String, Object>();

        params.add("currency", walletWithdraw.getCurrency().toString());
        params.add("currencyChainType", walletWithdraw.getCurrencyChainType().toString());
        params.add("txHash",walletWithdraw.getTxHash());
        params.add("withdrawAmount",walletWithdraw.getWithdrawAmount().toString());
        params.add("inputDate",walletWithdraw.getInputDate().toString());
        params.add("id",walletWithdraw.getId().toString());
        params.add("sysNum",walletWithdraw.getSysNum());

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, initHttpHeader());
        //执行HTTP请求
        ResponseEntity<String> response = restTemplate.exchange(depositUrl, HttpMethod.POST, requestEntity, String.class);

        WalletWithdraw wwdUpdateStatus=new WalletWithdraw();
        wwdUpdateStatus.setId(walletWithdraw.getId());
        /**更新成功**/
        if(response!=null && response.getBody()!=null && response.getBody().contains("success")){
            wwdUpdateStatus.setStatus(40);
        }else{
            if(walletWithdraw.getStatus()==20)
                wwdUpdateStatus.setStatus(30);
            else if(walletWithdraw.getStatus()<33)
                wwdUpdateStatus.setStatus(walletWithdraw.getStatus()+1);
            log.info("提币成功,通知失败：walletDeposit="+ JSONUtil.toJsonStr(walletWithdraw));
        }
        walletWithdrawServiceImap.updateById(wwdUpdateStatus);
    }

    HttpHeaders initHttpHeader(){
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return  headers;
    }



}
